package com.joinlink.omiis.commons.persistence.impl;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.joinlink.omiis.commons.persistence.preferences.IPreferenceKeys;
import com.joinlink.omiis.commons.persistence.util.ConfigUtils;

public class DBCPPool {

	private static Logger logger = LoggerFactory.getLogger(DBCPPool.class);

	private static BasicDataSource basicDataSource = null;
	private static DBCPPool instance = null;
	private static Object lock = new Object();

	/**
	 * Singleton
	 * 
	 * @throws Exception
	 */
	private DBCPPool() throws Exception {
		initialize();
	}

	public static DBCPPool getInstance() {
		if (instance == null) {
			synchronized (lock) {
				if (instance == null) {
					try {
						instance = new DBCPPool();
					} catch (Exception e) {
						logger.info(e.getMessage(), e);
					}
				}
			}
		}
		return instance;
	}

	public Connection createConnection() throws Exception {
		long t1 = System.currentTimeMillis();

		// if (basicDataSource == null || basicDataSource.isClosed()) {
		// synchronized (lock) {
		// if (basicDataSource == null || basicDataSource.isClosed()) {
		// initialize();
		// }
		// }
		// }
		Connection conn = null;
		conn = basicDataSource.getConnection();
		if (conn == null) {
			throw new RuntimeException("获取数据库连接失败！");
		}
		long t2 = System.currentTimeMillis();
		logger.info("获取数据库连接耗时：" + (t2 - t1) + "毫秒，conn=" + conn);
		logger.info("连接池信息：initialSize=" + basicDataSource.getInitialSize() + "，maxIdle=" + basicDataSource.getMaxIdle()
				+ "，minIdle=" + basicDataSource.getMinIdle() + "，maxTotal=" + basicDataSource.getMaxTotal() + "，"
				+ "，numActive=" + basicDataSource.getNumActive() + "，numIdle=" + basicDataSource.getNumIdle());
		return conn;
	}

	/**
	 * 初始化数据库连接池
	 * 
	 * @throws Exception
	 */
	private void initialize() throws Exception {
		long t1 = System.currentTimeMillis();
		logger.info("开始初始化数据源......");
		Properties jdbcProperties = ConfigUtils.loadConfig(new File(IPreferenceKeys.JDBC_CONFIG_PATH));

		basicDataSource = new BasicDataSource();
		BasicDataSourceFactory bdsFactory = new BasicDataSourceFactory();
		basicDataSource = bdsFactory.createDataSource(jdbcProperties);
		if (basicDataSource == null || basicDataSource.isClosed()) {
			throw new RuntimeException("数据库连接池初始化失败！");
		}
		long t2 = System.currentTimeMillis();
		logger.info("数据库连接池初始化完成，耗时：" + (t2 - t1) + "毫秒。");
	}

	/**
	 * 关闭数据源
	 */
	public void shutdown() {
		long t1 = System.currentTimeMillis();
		logger.info("开始关闭数据库连接池......");
		if (basicDataSource != null && !basicDataSource.isClosed()) {
			try {
				basicDataSource.close();
			} catch (SQLException e) {
				throw new RuntimeException("数据库连接池关闭发生异常：" + e.getMessage(), e);
			}
		}
		long t2 = System.currentTimeMillis();
		logger.info("数据库连接池关闭完成，耗时：" + (t2 - t1) + "毫秒。");
	}

	public static void main(String[] args) {

	}

}
